package com.zhiyou100.test.test02.homework;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yang
 * @className StudentManagement
 * @packageName com.zhiyou100.test.test02.homework
 * @Description TODO xml 实现 学生的增删该查
 * @date 2020-08-07 22:30
 */
public class StudentManagement {
    /**
     * xml 文件路径
     */
    public static final String PATH = "src/main/resources/student.xml";


    /**
     * @return org.dom4j.Document
     * @Description TODO 根据 xml 文件获取 document 对象
     * @name getDocument
     * @param: [fileName]
     * @date 8/8/20 14:36
     * @author yang
     */
    public static Document getDocument(String fileName) {
        try {
            return new SAXReader().read(fileName);
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @return void
     * @Description TODO 把修改后的 Document 写回 xml 文件
     * @name setDocument
     * @param: [document]
     * @date 8/8/20 15:34
     * @author yang
     */
    public static void setDocument(Document document) {
        // createPrettyPrint 设置不紧凑
        OutputFormat compactFormat = OutputFormat.createPrettyPrint();
        // createCompactFormat 设置紧凑
        //OutputFormat compactFormat = OutputFormat.createCompactFormat();
        compactFormat.setEncoding("utf-8");
        XMLWriter xmlWriter = null;
        try (
                // 此代码块会自动关流
                FileOutputStream fileOutputStream = new FileOutputStream(PATH);
                final OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream)
        ) {
            xmlWriter = new XMLWriter(outputStreamWriter, compactFormat);
            xmlWriter.write(document);
            xmlWriter.flush();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                assert xmlWriter != null;
                xmlWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @return int
     * @Description TODO 获取最大的 sid
     * @name getMaxSid
     * @param: []
     * @date 8/8/20 14:22
     * @author yang
     */
    public static int getMaxSid() {
        // 记录最大的 sid
        int maxSid = 0;

        // 获取根节点
        Element rootElement = getDocument(PATH).getRootElement();

        // 获取所有的 student 节点
        List student = rootElement.elements("student");

        // 找到到最大的
        for (Object o : student) {
            if (o instanceof Element) {
                // 转型
                Element element = (Element) (o);
                // 获取 属性 sid 的值
                int sid = Integer.parseInt(element.attributeValue("sid"));
                maxSid = Math.max(sid, maxSid);
            }
        }

        return maxSid;
    }

    /**
     * @return boolean
     * @Description TODO 判断是否存在该 sid , ture 存在、false 不存在
     * @name exist
     * @param: [student]
     * @date 8/8/20 15:01
     * @author yang
     */
    public static boolean exist(int form) {

        if (form == 0) {
            // 合理性判断
            return false;
        }

        boolean flag = false;

        // 获取根节点
        Element rootElement = getDocument(PATH).getRootElement();

        // 获取所有的 student 节点
        List student = rootElement.elements("student");

        // 找到到最大的
        for (Object o : student) {
            if (o instanceof Element) {
                // 转型
                Element element = (Element) (o);
                // 获取 属性 sid 的值
                int sid = Integer.parseInt(element.attributeValue("sid"));
                if (sid == form) {
                    flag = true;
                    break;
                }
            }
        }

        return flag;
    }

    /**
     * @return void
     * @Description TODO 添加一个
     * @name addOneStudent
     * @param: [from]
     * @date 8/8/20 15:50
     * @author yang
     */
    public static void addOneStudent(Student from) {

        if (from == null) {
            return;
        }

        // 获取 root 根目录
        Document document = getDocument(PATH);
        Element rootElement = document.getRootElement();
        // 创建一个 student
        final Element student = rootElement.addElement("student");
        // 设置属性
        student.addAttribute("sid", (getMaxSid() + 1) + "");
        // 添加子标签，设置文本内容
        student.addElement("sname").setText(from.getSname());
        student.addElement("sex").setText(from.getSex());
        student.addElement("sage").setText(from.getSage() + "");
        student.addElement("score").setText(from.getScore() + "");
        // 设置回 xml 文件
        setDocument(document);
    }

    /**
     * @return boolean
     * @Description TODO 根据 sid 删除一个
     * @name delOne
     * @param: [sid]
     * @date 8/8/20 16:02
     * @author yang
     */
    public static boolean delOne(int sid) {
        boolean flag = false;
        if (!exist(sid)) {
            return false;
        }

        final Document document = getDocument(PATH);
        final Element root = document.getRootElement();

        for (Object o : root.elements()) {
            if (o instanceof Element) {
                // 转换为
                final Element element = (Element) (o);
                // sid = form sid
                if ((sid + "").equals(element.attributeValue("sid"))) {
                    // 删除
                    root.remove(element);
                    flag = true;
                    break;
                }
            }
        }

        setDocument(document);
        return flag;
    }


    /**
     * @return void
     * @Description TODO 更新一个
     * @name updateOne
     * @param: [from]
     * @date 8/8/20 16:14
     * @author yang
     */
    public static void updateOne(Student from) {

        if (from == null || from.getSid() == 0 || !exist(from.getSid())) {
            // 判断 合理性
            return;
        }

        // 获取document
        final Document document = getDocument(PATH);
        // 获取根目录
        final Element root = document.getRootElement();

        // 遍历每一个 根目录的子元素
        for (Object o : root.elements()) {
            if (o instanceof Element) {
                // 转换为 Element
                final Element element = (Element) (o);
                // sid = form sid ，判断同一个 student
                if ((from.getSid() + "").equals(element.attributeValue("sid"))) {
                    // 设置
                    element.element("sname").setText(from.getSname());
                    element.element("sex").setText(from.getSex());
                    element.element("sage").setText(from.getSage() + "");
                    element.element("score").setText(from.getScore() + "");
                    // 跳出
                    break;
                }
            }
        }

        // 刷新
        setDocument(document);
    }

    /**
     * @return com.zhiyou100.test.test02.homework.Student
     * @Description TODO 查找一个 根据 sid
     * @name findOne
     * @param: [form]
     * @date 8/8/20 16:25
     * @author yang
     */
    public static Student findOne(int form) {
        if (form == 0 || !exist(form)) {
            // 合理性判断
            return null;
        }

        Student student = null;

        // 获取根节点
        Element rootElement = getDocument(PATH).getRootElement();

        // 获取所有的 student 节点
        List students = rootElement.elements("student");

        // 找到
        for (Object o : students) {
            if (o instanceof Element) {
                // 转型
                Element element = (Element) (o);
                // 获取 属性 sid 的值
                int sid = Integer.parseInt(element.attributeValue("sid"));
                if (sid == form) {
                    final String sname = element.element("sname").getText();
                    final String sex = element.element("sex").getText();
                    final String sage = element.element("sage").getText();
                    final String score = element.element("score").getText();
                    student = new Student(sid, sname, sex, Integer.parseInt(sage), Double.parseDouble(score));
                    return student;
                }
            }
        }

        return student;


    }

    /**
     * @return java.util.ArrayList<com.zhiyou100.test.test02.homework.Student>
     * @Description TODO 获取所有的学生
     * @name getAll
     * @param: []
     * @date 8/8/20 19:35
     * @author yang
     */
    public static ArrayList<Student> getAll() {
        final ArrayList<Student> all = new ArrayList<>();


        Student student = null;

        // 获取根节点
        Element rootElement = getDocument(PATH).getRootElement();

        // 获取所有的 student 节点
        List students = rootElement.elements("student");

        // 找到
        for (Object o : students) {
            if (o instanceof Element) {
                // 转型
                Element element = (Element) (o);
                // 获取 属性 sid 的值
                int sid = Integer.parseInt(element.attributeValue("sid"));
                final String sname = element.element("sname").getText();
                final String sex = element.element("sex").getText();
                final String sage = element.element("sage").getText();
                final String score = element.element("score").getText();
                student = new Student(sid, sname, sex, Integer.parseInt(sage), Double.parseDouble(score));
                all.add(student);

            }
        }

        return all;


    }

}
